package com.kyzh.core.pager.gamelist

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gushenge.core.beans.YuYue
import com.gushenge.core.requests.GameRequest
import com.kyzh.core.R
import com.kyzh.core.adapters.BiaoqianAdapter
import com.kyzh.core.databinding.ItemGameYuyueBinding
import kotlinx.android.synthetic.main.fragment_gameyuyue.*


class GameYuYueFragment : Fragment() {

    private val bean = arrayListOf<YuYue>()
    private val adapter = Adapter(R.layout.item_game_yuyue, bean)
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_gameyuyue, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        recyclerView.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollHorizontally(): Boolean {
                return false
            }
        }
        recyclerView.adapter = adapter
        initData()
        root.setOnRefreshListener {
            initData()
        }
    }

    private fun  initData(){
        GameRequest.yuyue {
            bean.clear()
            bean.addAll(it)
            adapter.notifyDataSetChanged()
        }
        root.isRefreshing = false
    }
    private inner class Adapter(layout:Int,beans:ArrayList<YuYue>):BaseQuickAdapter<YuYue,BaseViewHolder>(layout,beans){
        override fun onItemViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
            DataBindingUtil.bind<ItemGameYuyueBinding>(viewHolder.itemView)
        }
        override fun convert(holder: BaseViewHolder, item: YuYue) {
            holder.getBinding<ItemGameYuyueBinding>()?.let {
                it.data =  item
                it.rank = holder.adapterPosition
            }

            val bq = holder.getView<RecyclerView>(R.id.bq)
            val yuyue = holder.getView<TextView>(R.id.tvDetail)
            bq.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
            bq.adapter = BiaoqianAdapter( item.biaoqian)

            yuyue.setOnClickListener {
                if (!item.is_yuyue){
                    GameRequest.yuyueAdd(item.id){
                        bean[holder.adapterPosition].is_yuyue = true
                        notifyDataSetChanged()
                    }
                }
            }
        }
    }
}